<template>
    <div style="padding-top: 1%">
        <Card :bordered="false" style="margin-left: 16%;margin-right: 1%" dis-hover>
            <p slot="title" style="font-size: larger;font-weight: bolder">用户管理 / 用户列表</p>
            <div>
                <div style="display: flex;justify-content: space-around">
                    <!--添加用户按钮-->
                    <Button type="primary" icon="md-add" @click="addUserModal=true">添加用户</Button>
                    <!--查询表单-->
                    <Form ref="queryVoRef" :model="queryVo" :label-width="80" inline>
                        <FormItem label="邮箱号：">
                            <Input v-model="queryVo.email" placeholder="请输入邮箱号(精确查询)" style="width: 250px"/>
                        </FormItem>
                        <FormItem label="昵称：">
                            <Input v-model="queryVo.nickName" placeholder="请输入昵称(模糊查询)" style="width: 250px"/>
                        </FormItem>
                        <FormItem>
                            <Button type="primary" icon="ios-search" @click="getUserInfo">查询</Button>
                            <Button style="margin-left: 8px" @click="handleReset()">重置</Button>
                        </FormItem>
                    </Form>
                </div>
                <Alert style="margin-top: 1%" show-icon>用户列表</Alert>
                <!--用户表格-->
                <div style="margin-top: 1%">
                    <Table :columns="tableReflect" :data="userInfo">
                        <template slot-scope="{ row }" slot="uheadpicture">
                            <img :src="row.uheadpicture" alt="" style="width: 60px;height: 60px">
                        </template>
                        <template slot-scope="{ row }" slot="usex">
                            <span>{{row.usex?'男':'女'}}</span>
                        </template>
                        <template slot-scope="{ row }" slot="uadmin">
                            <ISwitch :value="row.uadmin" @on-change="changeAdmin(row.uid,$event)">
                                <span slot="open">是</span>
                                <span slot="close">否</span>
                            </ISwitch>
                        </template>
                        <!--修改用户-->
                        <template slot-scope="{ row }" slot="action">
                            <Button type="warning" size="small" @click="showeditUserModal(row)">修改</Button>
                        </template>
                    </Table>
                </div>
            </div>
            <!--分页-->
            <div style="margin-top: 1.5%">
                <Page style="height: 20px" :total="queryVo.total"
                      show-elevator show-sizer show-total :page-size="queryVo.pageSize" :page-size-opts="pageSizeFixed"
                      @on-change="changePageNum" @on-page-size-change="changePageSize"/>
            </div>
        </Card>
        <!--添加用户对话框-->
        <Modal title="添加用户"
               v-model="addUserModal"
               class-name="vertical-center-modal"
               @on-ok="addUser('userRef')"
               ok-text="添加">
            <Form ref="userRef" :model="user" :rules="userRule" :label-width="80">
                <FormItem label="手机号" prop="phone">
                    <Input v-model="user.phone" placeholder="请输入手机号"/>
                </FormItem>
                <FormItem label="密码" prop="password">
                    <Input type="password" v-model="user.password" placeholder="请输入密码"/>
                </FormItem>
                <FormItem label="确认密码" prop="password2">
                    <Input type="password" v-model="user.password2" placeholder="请再次输入密码"
                           @keyup.native.enter="addUser('userRef')"/>
                </FormItem>
            </Form>
        </Modal>
        <!--修改用户信息-->
        <Modal title="修改用户信息"
               v-model="editUserModal"
               class-name="vertical-center-modal"
               @on-ok="submitEditUser('editUserRef')"
               ok-text="修改">
            <Form ref="editUserRef" :model="editUser" :rules="editUserRule" :label-width="80">
                <FormItem label="昵称" prop="uNickname">
                    <Input v-model="editUser.uNickname" placeholder="请输入昵称"/>
                </FormItem>
                <FormItem label="性别">
                    <RadioGroup v-model="editUser.uSex">
                        <Radio :label="1">男</Radio>
                        <Radio :label="0">女</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="生日" prop="uBirthday">
                    <Row>
                        <ICol span="11">
                            <DatePicker type="date" placeholder="请选择生日" v-model="editUser.uBirthday"></DatePicker>
                        </ICol>
                    </Row>
                </FormItem>
                <FormItem label="邮箱">
                    <Input v-model="editUser.uEmail" placeholder="请输入邮箱"
                           @keyup.native.enter="submitEditUser('editUserRef')"/>
                </FormItem>
            </Form>
        </Modal>
    </div>
</template>

<script>
  export default {
    data() {
      // 自定义手机号验证
      const phoneValidate = (rule, value, callback) => {
        if (!(/^1[3456789]\d{9}$/.test(value))) {
          callback(new Error('手机号码有误，请重填'))
        } else {
          callback()
        }
      }
      // 密码重复验证
      const pwdCalidate = (rule, value, callback) => {
        if (value !== this.user.password) {
          callback(new Error('两次密码不一致，请确认后再提交'))
        } else {
          callback()
        }
      }
      return {
        queryVo: {
          pageNum: 1,
          pageSize: 5,
          email: '',
          nickName: '',
          total: 0
        },
        // 表头映射
        tableReflect: [
          {
            title: '编号',
            key: 'uid'
          },
          {
            title: '昵称',
            key: 'unickname'
          },
          {
            title: '头像',
            slot: 'uheadpicture'
          },
          {
            title: '性别',
            slot: 'usex'
          },
          {
            title: '手机号',
            key: 'uphone'
          },
          {
            title: '生日',
            key: 'uBirthday'
          },
          {
            title: '管理员',
            slot: 'uadmin'
          },
          {
            title: '邮箱',
            key: 'uemail'
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center'
          }
        ],
        // 响应数据
        userInfo: [],
        // 每页个数
        pageSizeFixed: [5, 10, 20, 50, 100],
        // 添加用户弹出层控制
        addUserModal: false,
        // 添加用户信息
        user: {
          phone: '',
          password: '',
          password2: ''
        },
        // 添加用户映射规则
        userRule: {
          phone: [
            { required: true, message: '手机号不能为空', trigger: 'blur' },
            { validator: phoneValidate, trigger: 'blur' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' }
          ],
          password2: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { validator: pwdCalidate, trigger: 'blur' }
          ]
        },
        // 修改的用户信息
        editUser: {
          uId: 0,
          uNickname: '',
          uEmail: '',
          uSex: 0,
          uBirthday: ''
        },
        // 修改用户对话框
        editUserModal: false,
        // 修改用户规则
        editUserRule: {
          uNickname: [
            { required: true, message: '昵称不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    mounted() {
      this.getUserInfo()
    },
    methods: {
      // 转换日期成yyyy-MM-dd格式
      formatDate(date) {
        var nowdate = new Date(date).toLocaleDateString().replace(/\//g, '-')
        return nowdate
      },
      // 重置表单
      handleReset(name) {
        this.queryVo.email = ''
        this.queryVo.nickName = ''
      },
      // 获取用户列表
      getUserInfo() {
        this.$http.get('user-back?pageNum=' + this.queryVo.pageNum + '&pageSize=' +
          this.queryVo.pageSize + '&email=' + this.queryVo.email + '&nickName=' +
          this.queryVo.nickName).then(res => {
          this.queryVo.total = res.data.count
          this.userInfo = res.data.data
        })
      },
      // 当前页码改变回调
      changePageNum(pagenum) {
        this.queryVo.pageNum = pagenum
        this.getUserInfo()
      },
      // 每页条数改变回调
      changePageSize(pageize) {
        this.queryVo.pageSize = pageize
        this.getUserInfo()
      },
      // 添加用户
      addUser(name) {
        this.$refs[name].validate((valid) => {
          if (!valid) return
          // 添加用户
          var params = new URLSearchParams()
          params.set('phone', this.user.phone)
          params.set('password', this.user.password)
          this.$http.post('user-back', params).then(res => {
            if (res.data.code === 0) {
              this.addUserModal = false
              this.$Message.success('用户添加成功')
              // 重新获取数据
              this.getUserInfo()
              // 清空表单内容
              this.$refs[name].resetFields()
            } else {
              this.$Message.error(res.data.msg)
              this.addUserModal = true
            }
          })
        })
      },
      // 设置管理员
      changeAdmin(row, res) {
        var rowInt = parseInt(row)
        var resInt = res ? 1 : 0
        // 设置管理员
        this.$http.patch(`user-back/${rowInt}/${resInt}`).then(res => {
          if (res.data.code === 0) {
            this.$Message.success('设置管理员成功')
          } else {
            this.$Message.error('设置管理员失败')
          }
        })
      },
      // 弹出修改用户信息对话框
      showeditUserModal(row) {
        this.editUserModal = true
        this.editUser.uId = row.uid
        this.editUser.uNickname = row.unickname
        this.editUser.uEmail = row.uemail
        this.editUser.uSex = row.usex ? 1 : 0
        this.editUser.uBirthday = row.uBirthday
      },
      // 提交修改
      submitEditUser(name) {
        this.$refs[name].validate(valid => {
          if (!valid) return
          this.editUser.uBirthday = this.formatDate(this.editUser.uBirthday)
          // 修改用户信息
          var params = new URLSearchParams(this.editUser)
          this.$http.put('user-back', params).then(res => {
            res = res.data
            if (res.code === 2005) {
              this.editUserModal = false
              this.$Message.success(res.msg)
              this.getUserInfo()
            } else {
              this.$Message.error(res.msg)
              this.editUserModal = true
            }
          })
        })
      }
    }
  }
</script>

<style scoped>
</style>
